package chances.epg.data.taglib;

import java.util.List;

import javax.servlet.jsp.JspException;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;

import chances.epg.commons.log.EpgLogFactory;
import chances.epg.commons.utils.URLUtils;
import chances.epg.data.taglib.page.PageInfo;
import chances.epg.entity.content.CategoryItem;
import chances.epg.navigator.context.AccessContextUtils;


/**
 * 多栏目
 * @author libf@chances.com.cn
 * Copyright Shanghai Chances.
 */
public class MultiCategoryItemTag extends QueryListTag{
	/**
	 * serialVersionUID.
	 */
	private static final long serialVersionUID = 678520967236283833L;
	private static final Logger logger = EpgLogFactory.getSystemLogger();
	private String codes;//多个编排栏目的代码,使用逗号分隔
	private int size = 10;//条目数
	
	@Override
	public int doEndTag() throws JspException {
		if(StringUtils.isBlank(this.codes)){
			return super.doEndTag();
		}
		
		String[] catCodes = StringUtils.split(this.codes, ",");
		
		try{
			this.queryItemByPage(catCodes);
		}catch(Throwable ex){
			logger.error("CategoryItemTag error",ex);
		}
		
		return super.doEndTag();
	}
	
	/**
	 * 分页查询.
	 */
	private void queryItemByPage(String[] catCodes) {
		PageInfo pageInfo = this.createPageInfo(size);
		List<CategoryItem> result = this.getContentService().getCategoryItemsByCodes(catCodes, this.start, pageInfo.getPageBean());
		this.setPageInfo(pageInfo);
		this.setCategoryItem(result);
	}
	
	/**
	 * 
	 * @param result
	 */
	private void setCategoryItem(List<CategoryItem> result) {
		int index = 0;
		for (CategoryItem categoryItem : result) {
			index ++;
			String url = navigateUrlFactory.generateURL(AccessContextUtils.getAccessContext(pageContext), categoryItem);
			url = URLUtils.appendParam(url, "pi", index+"");
			categoryItem.setUrl(url);
		}
		
		this.setCollectionResult(result);
	}

	public String getCodes() {
		return codes;
	}

	public void setCodes(String codes) {
		this.codes = codes;
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}
}
